#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys

IncludePath="/var/coopip/djangoproject/include"
if(not IncludePath in sys.path):
    sys.path.append(IncludePath)


    
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime

#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject.settings
setup_environ(djangoproject.settings)
from djangoproject.models import *
from django.contrib.gis.geos import GEOSGeometry
import CIS, AMR, OMS, GIS
#********************Setup psycopg2 and django section********************


import urllib
import httplib

import datetime
        



Locations = list(CIS.Locinfodetl.objects.all().filter(idlecode='00'))
YardLightDict = {}
for location in Locations:
    YardLightNumber = 1
    while (YardLightNumber < 5):
        YardLightString = str(eval("location.yardlightinfo_00" + str(YardLightNumber))[:20])
        YardLightNumber = YardLightNumber + 1
        Quantity = int(YardLightString[10:14])
        if(not Quantity):
            continue
        if(not YardLightDict.has_key(location.location)):
            YardLightDict[location.location] = 0
        YardLightDict[location.location] = YardLightDict[location.location] + Quantity

MeterLocationDict = {}
Meters = list(CIS.Meterdetl.objects.filter(idlecode='00'))
for meter in Meters:
    MeterLocationDict[meter.location] = meter.meter


GIS.Coopgisyardlightassociatedwithmeternumber.objects.all().delete()
Count = 1
for key in YardLightDict:
    New=GIS.Coopgisyardlightassociatedwithmeternumber()
    New.id = Count
    try: 
        New.meternumber = MeterLocationDict[key].lstrip('0')
    except KeyError:
        print "Skipping:  " + str(key) + ' no Meter found.'
    New.quantity = YardLightDict[key]
    New.updatedatetime=datetime.datetime.now()
    New.save()
    Count = Count + 1





